package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.Query;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerMainOriginal;
import com.isunland.managesystem.entity.CustomerMainOriginal.rCustomerMain;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import org.json.JSONException;

/**
 * 客户详情
 *
 * @author wangyanan
 */
public class CustomerDetailFragment extends BaseFragment
    implements OnClickListener, OnPoiSearchListener {
  public static final String EXTRA_TYPE = "com.isunland.managesystem.EXTRA_TYPE";
  public static final int VALUE_ADD = 1;
  public static final int VALUE_ALTER = 2;
  public static final int VALUE_READ = 3;
  protected static final String EXTRA_CUSTOMER_DETAIL =
      "com.isunland.managesystem.EXTRA_CUSTOMER_detail";
  private static final int REQUEST_DISTRICT = 0;
  private static final int REQUEST_UNIT_TYPE = 1;
  private static final int REQUEST_ALTER = 2;
  private static final int REQUEST_DELETE = 3;
  private static final int REQUEST_SUBMIT = 4;
  private static final int REQUEST_CHARGE = 5;
  private static final int REQUEST_STAGE = 8;//最新阶段
  private static final int REQUEST_RESOURCE = 9;//客户来源
  private static final int SAVE = 6;//保存
  private static final int SAVE_SUBMIT = 7;//保存并提交
  private static final int REQUEST_PUBLISH = 10;//审核通过
  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private CustomerMainOriginal.rCustomerMain mCustomerDetail;
  private int mType;

  private EditText mETCustomerName;
  private TextView mTvCustomerDistrict;
  private TextView mTvUnitType;
  private EditText mEtCustomerMainBusiness;
  private EditText mEtCustomerContactPeople;
  private EditText mEtCustomerContactPhone;
  private TextView mTvCustomerCharge;
  private TextView tvCustomerStatus;
  private TextView tvCustomerSource;
  private EditText etLinkmanEmail;
  private EditText etPostCode;
  private EditText etCustomerAddress;
  private EditText etRemark;
  private TextView tvDataStatus;
  private TextView tvRegStaffName;
  private TextView tvRegDate;
  private TextView tvCheckStaffName;
  private TextView tvCheckDate;

  private String mDistrictCode;
  private String mUnitType;
  private String mCustomerStage;//最新阶段
  private String mCustomerSource;//客户来源
  private String mChargeJobNo;
  private String id = "";//本条记录id
  private String mUnitCode;
  private SingleLineView slvWeChatNumber;

  public static CustomerDetailFragment newInstance(rCustomerMain customerDetail, int type) {
    Bundle argsBundle = new Bundle();
    argsBundle.putSerializable(EXTRA_CUSTOMER_DETAIL, customerDetail);
    argsBundle.putSerializable(EXTRA_TYPE, type);
    CustomerDetailFragment fragment = new CustomerDetailFragment();
    fragment.setArguments(argsBundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());
    mCustomerDetail = (rCustomerMain) getArguments().getSerializable(EXTRA_CUSTOMER_DETAIL);
    mType = getArguments().getInt(EXTRA_TYPE);
    if (VALUE_ADD == mType) {
      setTitleCustom(R.string.customer_detail_add);
    } else if (VALUE_READ == mType) {
      setTitleCustom(R.string.customer_infor);
    } else if (VALUE_ALTER == mType) {
      setTitleCustom(R.string.customer_detail_alter);
    }
    if (mCustomerDetail == null) {
      //添加
      id = UUID.randomUUID().toString();
      mCustomerDetail = new CustomerMainOriginal().new rCustomerMain();
      mUnitType = "";
      mDistrictCode = "";
      mCustomerSource = "";
      mCustomerStage = "";
      mChargeJobNo = "";
      mUnitCode = "";
    } else {
      id = mCustomerDetail.getId();
      mUnitType = null == mCustomerDetail.getCustomerKindCode() ? ""
          : mCustomerDetail.getCustomerKindCode();
      mDistrictCode =
          null == mCustomerDetail.getDistrictCode() ? "" : mCustomerDetail.getDistrictCode();
      mCustomerSource =
          null == mCustomerDetail.getCustomerSource() ? "" : mCustomerDetail.getCustomerSource();
      mCustomerStage =
          null == mCustomerDetail.getCustomerStatus() ? "" : mCustomerDetail.getCustomerStatus();
      mChargeJobNo =
          null == mCustomerDetail.getChargeManIds() ? "" : mCustomerDetail.getChargeManIds();
      mUnitCode = null == mCustomerDetail.getUnitCode() ? "" : mCustomerDetail.getUnitCode();
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_customer_detail, container, false);
    findViews(v);
    initView();
    return v;
  }

  public void initView() {
    if (VALUE_ADD == mType) {
      mTvUnitType.setOnClickListener(this);
      mTvCustomerDistrict.setOnClickListener(this);
      mTvCustomerCharge.setOnClickListener(this);
      tvCustomerStatus.setOnClickListener(this);
      tvCustomerSource.setOnClickListener(this);
      tvDataStatus.setText(R.string.draft);
      tvRegStaffName.setText(mUser.getRealName());

      //noinspection deprecation
      tvRegDate.setText(MyDateUtil.parseDateToString(new Date()));
    } else {
      if (VALUE_READ == mType) {
        mTvUnitType.setEnabled(false);
        mTvCustomerDistrict.setEnabled(false);
        mTvCustomerCharge.setEnabled(false);
        tvCustomerStatus.setEnabled(false);
        tvCustomerSource.setEnabled(false);
        mEtCustomerContactPeople.setEnabled(false);
        mEtCustomerContactPhone.setEnabled(false);
        slvWeChatNumber.setInputEnabled(false);
        mEtCustomerMainBusiness.setEnabled(false);
        mETCustomerName.setEnabled(false);
        etLinkmanEmail.setEnabled(false);
        etPostCode.setEnabled(false);
        etCustomerAddress.setEnabled(false);
        etRemark.setEnabled(false);
      }

      mEtCustomerContactPeople.setText(mCustomerDetail.getContactManNames());
      mEtCustomerContactPhone.setText(mCustomerDetail.getContactNum());
      slvWeChatNumber.setTextContent(mCustomerDetail.getWeChatCode());
      mEtCustomerMainBusiness.setText(mCustomerDetail.getMainBusiness());
      mETCustomerName.setText(mCustomerDetail.getCustomerName());
      mTvCustomerDistrict.setText(mCustomerDetail.getDistrictDesc());
      mTvUnitType.setText(mCustomerDetail.getCustomerKindName());
      mTvCustomerCharge.setText(mCustomerDetail.getChargeManNames());

      tvCustomerStatus.setText(mCustomerDetail.getCustomerStatusName());
      tvCustomerSource.setText(mCustomerDetail.getCustomerSourceName());
      etLinkmanEmail.setText(mCustomerDetail.getLinkmanEmail());
      etPostCode.setText(mCustomerDetail.getPostCode());
      etCustomerAddress.setText(mCustomerDetail.getCustomerAddress());
      etRemark.setText(mCustomerDetail.getRemark());
      tvDataStatus.setText(DataStatus.map.get(mCustomerDetail.getDataStatus()).getStatusName());
      tvRegStaffName.setText(mCustomerDetail.getRegStaffName());
      tvRegDate.setText(mCustomerDetail.getRegDate());
      tvCheckStaffName.setText(mCustomerDetail.getCheckStaffName());
      tvCheckDate.setText(mCustomerDetail.getCheckDate());
    }
  }

  private void findViews(View v) {
    mETCustomerName = (EditText) v.findViewById(R.id.et_customerName_customerDetailFragment);
    mTvCustomerDistrict =
        (TextView) v.findViewById(R.id.tv_customerDistrict_customerDetailFragment);
    mTvUnitType = (TextView) v.findViewById(R.id.tv_unitType_customerDetailFragment);
    mEtCustomerMainBusiness =
        (EditText) v.findViewById(R.id.et_customerMainBusiness_customerDetailFragment);
    mEtCustomerContactPeople =
        (EditText) v.findViewById(R.id.et_customerContactPeople_customerDetailFragment);
    mEtCustomerContactPhone =
        (EditText) v.findViewById(R.id.et_customerContactPhone_customerDetailFragment);
    slvWeChatNumber = (SingleLineView) v.findViewById(R.id.slv_weChatNumber);
    mTvCustomerCharge = (TextView) v.findViewById(R.id.et_customerCharge);
    tvCustomerStatus = (TextView) v.findViewById(R.id.tv_customerStage);
    tvCustomerSource = (TextView) v.findViewById(R.id.tv_customerSource);
    etLinkmanEmail = (EditText) v.findViewById(R.id.et_linkmanEmail);
    etPostCode = (EditText) v.findViewById(R.id.et_postCode);
    etCustomerAddress = (EditText) v.findViewById(R.id.et_customerAddress);
    etRemark = (EditText) v.findViewById(R.id.et_remark);
    tvDataStatus = (TextView) v.findViewById(R.id.tv_dataStatus);
    tvRegStaffName = (TextView) v.findViewById(R.id.tv_regStaffName);
    tvRegDate = (TextView) v.findViewById(R.id.tv_regDate);
    tvCheckStaffName = (TextView) v.findViewById(R.id.tv_checkStaffName);
    tvCheckDate = (TextView) v.findViewById(R.id.tv_checkDate);
    mTvUnitType.setOnClickListener(this);
    mTvCustomerDistrict.setOnClickListener(this);
    mTvCustomerCharge.setOnClickListener(this);
    tvCustomerStatus.setOnClickListener(this);
    tvCustomerSource.setOnClickListener(this);
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {

      case R.id.tv_customerDistrict_customerDetailFragment:
        showDialog(REQUEST_DISTRICT);
        break;
      case R.id.tv_customerStage:
        showDialog(REQUEST_STAGE);
        break;

      //客户来源
      case R.id.tv_customerSource:
        showDialog(REQUEST_RESOURCE);
        break;

      case R.id.tv_unitType_customerDetailFragment:

        showDialog(REQUEST_UNIT_TYPE);
        break;
      case R.id.et_customerCharge:
        Intent intent = new Intent(getActivity(), SearchPersonMultipleActicity.class);
        intent.putExtra(SearchPersonMultipleFragment.EXTRA_FROM,
            SearchPersonMultipleFragment.VALUE_COMMON);
        intent.putExtra(SearchPersonMultipleFragment.EXTRA_JOB, mChargeJobNo);
        startActivityForResult(intent, REQUEST_CHARGE);
        break;
      default:
        break;
    }
  }

  /**
   * @param type 0代表地区,1代表单位类型
   */
  private void showDialog(int type) {
    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (type) {
      case REQUEST_DISTRICT:
        dialog = new DistrictDialogFragment();
        break;
      case REQUEST_STAGE:
        dialog = CustomerDialogFragment.newInstance(
            CustomerDialogFragment.VALUE_TYPE_CUSTOMER_UNIT_STATE);
        break;
      case REQUEST_RESOURCE:
        //客户来源
        dialog =
            CustomerDialogFragment.newInstance(CustomerDialogFragment.VALUE_TYPE_CUSTOMER_RESOURCE);
        break;
      case REQUEST_UNIT_TYPE:
        dialog = new UnitTypeDialogFragment();
        break;
      case REQUEST_DELETE:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        break;
      case REQUEST_SUBMIT:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.cannotEdit);
        break;
      case SAVE_SUBMIT:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.cannotEdit);
        break;
      case REQUEST_PUBLISH:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.submitConfirm);
        break;

      default:
        return;
    }

    dialog.setTargetFragment(CustomerDetailFragment.this, type);
    dialog.show(fm, "");
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.menu_customer_detail, menu);
    if (VALUE_ADD == mType) {
      //保存,保存并提交
      menu.getItem(1).setVisible(true);
      menu.getItem(2).setVisible(true);
      menu.getItem(2).setTitle(R.string.saveAndSubmit);
    } else if (VALUE_ALTER == mType) {
      //保存
      menu.getItem(1).setVisible(true);
    } else if (VALUE_READ == mType) {
      //草稿: 修改,提交,删除
      //提交: 审核,退回
      //退回: 修改,提交,审核,删除
      //审核: 退回
      if (DataStatus.NEW.equalsIgnoreCase(mCustomerDetail.getDataStatus())) {
        menu.getItem(0).setVisible(true);
        menu.getItem(2).setVisible(true);
        menu.getItem(5).setVisible(true);
        menu.getItem(6).setVisible(true);
      } else if (DataStatus.SUBMIT.equalsIgnoreCase(mCustomerDetail.getDataStatus())) {
        menu.getItem(0).setVisible(true);
        menu.getItem(3).setVisible(true);
        menu.getItem(4).setVisible(true);
      } else if (DataStatus.NEWBACK.equalsIgnoreCase(mCustomerDetail.getDataStatus())) {
        menu.getItem(0).setVisible(true);
        menu.getItem(2).setVisible(true);
        menu.getItem(3).setVisible(true);
        menu.getItem(5).setVisible(true);
        menu.getItem(6).setVisible(true);
      } else if (DataStatus.PUBLIS.equalsIgnoreCase(mCustomerDetail.getDataStatus())) {
        menu.getItem(0).setVisible(true);
        menu.getItem(4).setVisible(true);
      }
    } else {
      super.onCreateOptionsMenu(menu, inflater);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    String createrId = "";// 创建人
    if (mCustomerDetail != null) {
      createrId = mCustomerDetail.getRegStaffId();
    }
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;

      case R.id.menu_item_save:
        saveCustomer(SAVE);
        return true;

      case R.id.menu_item_location:
        if (mCustomerDetail == null) {
          ToastUtil.show(R.string.emptyCustomer);
          return false;
        }
        String district = mCustomerDetail.getDistrictDesc();
        String name;
        if (!TextUtils.isEmpty(mCustomerDetail.getCustomerAddress())) {
          name = mCustomerDetail.getCustomerAddress();
          ToastUtil.show(name);
        } else {
          name = mCustomerDetail.getCustomerName();
          if (TextUtils.isEmpty(name) || TextUtils.isEmpty(district)) {
            ToastUtil.show(R.string.emptyNameOrDistrict);
            return false;
          }
        }
        searchByName(name, district);
        return true;
      case R.id.menu_item_alter:
        if (!mUser.isCreater(createrId)) {
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        }

        if (mCustomerDetail.getDataStatus().equalsIgnoreCase("new")
            || mCustomerDetail.getDataStatus().equalsIgnoreCase("newback")) {
          Intent i = new Intent(getActivity(), CustomerDetailActivity.class);
          i.putExtra(EXTRA_CUSTOMER_DETAIL, mCustomerDetail);
          i.putExtra(EXTRA_TYPE, VALUE_ALTER);
          startActivityForResult(i, REQUEST_ALTER);
        } else {
          Toast.makeText(getActivity(), R.string.draftOrAbort, Toast.LENGTH_SHORT).show();
        }

        return true;
      case R.id.menu_item_delete:
        if (!mUser.isCreater(createrId)) {
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        }

        if (mCustomerDetail.getDataStatus().equalsIgnoreCase("new")
            || mCustomerDetail.getDataStatus().equalsIgnoreCase("newback")) {

          showDialog(REQUEST_DELETE);
        } else {
          Toast.makeText(getActivity(), R.string.draftOrAbort, Toast.LENGTH_SHORT).show();
        }
        return true;
      case R.id.menu_item_submit:
        //保存并提交，先保存在调提交
        if (VALUE_ADD == mType) {
          saveCustomer(SAVE_SUBMIT);
        } else {
          //提交
          if (!mUser.isCreater(createrId)) {
            Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
            ToastUtil.show("只能提交自己登记的记录!");
            return true;
          } else {
            showDialog(REQUEST_SUBMIT);
          }
        }
        return true;

      case R.id.menu_item_publish:
        //审核通过
        showDialog(REQUEST_PUBLISH);
        return true;

      case R.id.menu_item_back:
        if (DataStatus.PUBLIS.equalsIgnoreCase(mCustomerDetail.getDataStatus())
            && !mCustomerDetail.getCheckStaffId().equalsIgnoreCase(mUser.getJobNumber())) {
          ToastUtil.show("只能退回自己审核的记录!");
        } else {
          //退回
          volleyPostSubmit(DataStatus.NEWBACK);
        }
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  /**
   * 通过公司名查询地理位置信息
   *
   * @param name 单位地址或客户名称
   * @param city 城市
   */
  private void searchByName(String name, String city) {
    // 搜索条件: 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域
    Query query = new PoiSearch.Query(name, "", city);
    query.setPageSize(10);
    query.setPageNum(0);
    // 初始化poiSearch对象
    PoiSearch poiSearch = new PoiSearch(getActivity(), query);
    // 设置回调数据的监听器
    poiSearch.setOnPoiSearchListener(this);
    MyUtils.showDialogLoading(getActivity());
    // 开始搜索
    poiSearch.searchPOIAsyn();
  }

  /**
   * @param requestCode 判断是保存还是保存并审核通过
   **/
  private void saveCustomer(int requestCode) {
    if (!MyUtils.isNetLink(getActivity())) {
      Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }
    boolean isEmpty = MyUtils.isEmptyText(mETCustomerName)
        || MyUtils.isEmptyText(mTvCustomerDistrict)
        || MyUtils.isEmptyText(tvCustomerStatus)
        || MyUtils.isEmptyText(tvCustomerSource)
        || MyUtils.isEmptyText(mTvCustomerCharge);
    if (isEmpty) {
      Toast.makeText(getActivity(), R.string.incomplete_message, Toast.LENGTH_SHORT).show();
      return;
    }
    if (!TextUtils.isEmpty(mEtCustomerContactPhone.getText().toString())) {

      @SuppressWarnings("deprecation") boolean isValidPhone =
          MyUtils.isPhoneNumberValid(mEtCustomerContactPhone.getText().toString());
      if (!isValidPhone) {
        Toast.makeText(getActivity(), R.string.notCorrectPhoneNumber, Toast.LENGTH_SHORT).show();
        return;
      }
    }
    if (SAVE == requestCode) {
      volleyPostSave(requestCode);
    } else if (SAVE_SUBMIT == requestCode) {
      showDialog(SAVE_SUBMIT);
    }
  }

  private void volleyPostSave(final int requestCode) {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_SAVE);

    ParamsNotEmpty params = new ParamsNotEmpty();

    params.put("id", id);
    params.put("customerName", mETCustomerName.getText().toString().trim());

    params.put("districtDesc", mTvCustomerDistrict.getText().toString().trim());
    params.put("districtCode", mDistrictCode);//区域

    params.put("customerStatus", mCustomerStage);
    params.put("customerStatusName", tvCustomerStatus.getText().toString().trim());//客户最新阶段

    params.put("customerKindCode", mUnitType);// 行业类别编码

    params.put("customerSource", mCustomerSource);// 客户来源
    params.put("customerSourceName", tvCustomerSource.getText().toString());

    params.put("mainBusiness", mEtCustomerMainBusiness.getText().toString());//主营业务

    params.put("contactNum", mEtCustomerContactPhone.getText().toString());//联系电话
    params.put("contactManNames", mEtCustomerContactPeople.getText().toString());// 联系人
    params.put("linkmanEmail", etLinkmanEmail.getText().toString());// 联系邮箱
    params.put("postCode", etPostCode.getText().toString().trim());// 联系邮编
    params.put("customerAddress", etCustomerAddress.getText().toString());// 单位地址
    params.put("remark", etRemark.getText().toString());// 备注
    params.put("chargeManIds", mChargeJobNo);
    params.put("chargeManNames", mTvCustomerCharge.getText().toString());// 客户负责人名称
    params.put("unitCode", mUnitCode);//判断只能看自己登记或负责人为自己的客户
    params.put("weChatCode", slvWeChatNumber.getTextContent());//判断只能看自己登记或负责人为自己的客户

    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage custoomerMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == custoomerMessage || null == custoomerMessage.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = custoomerMessage.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            if (SAVE == requestCode) {
              Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            } else if (SAVE_SUBMIT == requestCode) {
              volleyPostSubmit(DataStatus.SUBMIT);
            }
          }
        } catch (JsonSyntaxException ignored) {
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_DISTRICT && data != null) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(DistrictDialogFragment.EXTRA_VALUE);
      mTvCustomerDistrict.setText(customerDialog.getName());
      mDistrictCode = customerDialog.getId();
    }
    if (requestCode == REQUEST_UNIT_TYPE && data != null) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(UnitTypeDialogFragment.EXTRA_VALUE);
      mTvUnitType.setText(customerDialog.getName());
      mUnitType = customerDialog.getId();
    }
    if (requestCode == REQUEST_STAGE && data != null) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(CustomerDialogFragment.EXTRA_VALUE);
      tvCustomerStatus.setText(customerDialog.getName());
      mCustomerStage = customerDialog.getId();
    }
    if (requestCode == REQUEST_RESOURCE && data != null) {
      CustomerDialog customerDialog =
          (CustomerDialog) data.getSerializableExtra(CustomerDialogFragment.EXTRA_VALUE);
      tvCustomerSource.setText(customerDialog.getName());
      mCustomerSource = customerDialog.getId();
    }

    if (requestCode == REQUEST_CHARGE && data != null) {
      String mCharge = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_NAME);
      mChargeJobNo = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_JOB);
      mUnitCode = data.getStringExtra(SearchPersonMultipleFragment.EXTRA_DEPCODE);
      if (!TextUtils.isEmpty(mCharge)) {
        mTvCustomerCharge.setText(mCharge);
      }
    }
    // 修改成功后会回到只读页面,这句代码可以返回列表.
    if (requestCode == REQUEST_ALTER) {
      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      volleyPostSubmit(DataStatus.SUBMIT);
    }
    if (requestCode == SAVE_SUBMIT) {
      volleyPostSave(SAVE_SUBMIT);
    }
    if (requestCode == REQUEST_PUBLISH) {
      volleyPostSubmit(DataStatus.PUBLIS);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private void volleyPostDelete() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mCustomerDetail.getId());

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        //noinspection EmptyCatchBlock
        try {
          MyUtils.dismissDialog();
          SuccessMessage custoomerMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == custoomerMessage || null == custoomerMessage.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = custoomerMessage.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void volleyPostSubmit(String dataStatus) {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_SUBMIT);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", id);
    params.put("dataStatus", dataStatus);

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        //noinspection EmptyCatchBlock
        try {
          MyUtils.dismissDialog();
          SuccessMessage custoomerMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == custoomerMessage || null == custoomerMessage.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = custoomerMessage.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            ToastUtil.show(R.string.success_operation);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {

        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  /**
   * 位置信息搜索结果回调方法
   */
  @Override public void onPoiSearched(PoiResult result, int rCode) {
    MyUtils.dismissDialog();
    // 返回码为1000,代表成功
    try {
      if (rCode == 1000) {
        List<PoiItem> poiItems = result.getPois();
        PoiItem item = poiItems.get(0);
        Intent i = new Intent(getActivity(), LocationActivity.class);
        i.putExtra(LocationFragment.EXTRA_NAME, item);
        startActivity(i);
      } else if (rCode == 1804) {
        Toast.makeText(getActivity(), R.string.networkError, Toast.LENGTH_SHORT).show();
      } else if (rCode == 1008) {
        Toast.makeText(getActivity(), R.string.keyError, Toast.LENGTH_SHORT).show();
      } else {
        Toast.makeText(getActivity(), R.string.otherError, Toast.LENGTH_SHORT).show();
      }
    } catch (Exception e) {
      LogUtil.e("locationError", e);
      ToastUtil.show(R.string.noLocationInfo);
    }
  }

  @Override public void onPoiItemSearched(PoiItem poiItem, int i) {

  }
}
